package com.raven.craft.code.generator.common.file;

import com.raven.craft.code.generator.common.constant.FileSuffix;
import com.raven.craft.code.generator.common.file.metadata.FileMetadata;
import com.raven.craft.code.generator.common.file.metadata.JavaFileMetadata;
import com.raven.craft.code.generator.common.file.template.HbsTemplateBuilder;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

@Getter
@ToString
@Slf4j
public class HbsFile implements File {

    private final FileMetadata metadata;
    private final String templatePath;
    private final Object vo;
    // 文件内容
    private final String content;

    public HbsFile(FileMetadata metadata, String templatePath, Object vo) {
        this.metadata = metadata;
        this.templatePath = templatePath;
        this.vo = vo;
        this.content = new HbsTemplateBuilder(getTemplatePath() + getMetadata().getSuffix().getCode(), getVo()).apply();
    }

    public HbsFile(String name, FileSuffix fileSuffix, String path, String templatePath, Object vo) {
        this(new FileMetadata(name, fileSuffix, path), templatePath, vo);
    }

    public HbsFile(String name, String path, String targetPackage, String templatePath, Object vo) {
        this(new JavaFileMetadata(name, path, targetPackage), templatePath, vo);
    }

    @Override
    @SneakyThrows
    public void output() {
        Assert.notNull(getMetadata(), "metadata cannot be null");
        Assert.notNull(getContent(), "content cannot be null");

        Path fileDirPath = Paths.get(getMetadata().getPath());
        if (!Files.exists(fileDirPath)) {
            Files.createDirectories(fileDirPath);
        }

        Path fullFilePath = Paths.get(getMetadata().getFullFilePath());
        log.info("output file to [{}]", fullFilePath);

        Files.write(fullFilePath,
                getContent().getBytes(),
                StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    }
}
